﻿using HCore;

namespace MEat
{
    public class Dummy : MoveEntity
    {
        public int playerId;

        public Steer<Dummy> steer => _steer;

        private readonly Steer<Dummy> _steer;

        private readonly GoalThink _brain;

        private Vector3 _target;

        public Dummy(int eType, HGame game) : base(eType, game)
        {
            _steer = new Steer<Dummy>(this);
            _brain = new GoalThink(this);
        }

        public void SetTarget(Vector3 target)
        {
            if (_target == target)
            {
                return;
            }

            _target = target;

            _brain.AddGoalSeekToPosition(target);
        }

        public override void Update(Fix deltaTime)
        {
            _brain.Process();
            UpdateMovement(deltaTime);
            base.Update(deltaTime);
        }

        private void UpdateMovement(Fix deltaTime)
        {
            Vector3 force = _steer.Calculate();
            if (force == Vector3.zero)
            {
                Fix BrakingRate = Fix.Ratio(1, 10);
                Vector3 friction = -velocity.normalized * BrakingRate;
                force = friction;
            }

            Vector3 accelerate = force / mass;
            velocity += accelerate * deltaTime;
            velocity.Truncate(maxSpeed);

            position += velocity * deltaTime;

            if (velocity != Vector3.zero)
            {
                forward = velocity.normalized;
            }
        }

        public override void Dispose()
        {
        }

        public override int CalculateChecksum()
        {
            return position.GetHashCode();
        }

        public bool IsAtPosition(Vector3 p)
        {
            return (position - p).sqrMagnitude < Fix.Ratio(1, 10);
        }
    }
}